<template>
  <div class="express-template-container base-page-container">
    <!-- 搜索区域 -->
    <common-search
      v-model="searchForm"
      :search-items="searchItemsConfig"
      @search="handleSearch"
      @reset="handleReset"
    />
    
    <!-- 操作按钮区域 -->
    <action-buttons
      :action-permissions="actionPermissions"
      :selected-data="selectedRows"
      :buttons-config="buttonsConfig"
      @add="handleAdd"
      @delete="handleDelete"
      @enable="handleEnable"
      @disable="handleDisable"
    />
    
    <!-- 表格区域 -->
    <custom-table
      :data="tableData"
      :columns="tableColumns"
      :loading="tableLoading"
      :current-page="pagination.currentPage"
      :page-size="pagination.pageSize"
      :total="pagination.total"
      table-id="express-template-table"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      
      <!-- 操作列自定义渲染 -->
      <template #operation="{ row }">
        <theme-button link @click="handleEdit(row)">编辑</theme-button>
        <theme-button link @click="handleDesign(row)">设计</theme-button>
        <theme-button link @click="handlePreview(row)">预览</theme-button>
	  </template>		
    </custom-table>
    
    <!-- 表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitleMap[dialogType]"
      width="500px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        class="dialog-form"
		style="padding-top: 20px;"
      >
        <!-- <div class="form-row">
          <el-form-item label="模板名称" prop="templateName">
            <el-input 
              v-model="formData.templateName"
              :disabled="dialogType === 'view'"
              placeholder="请输入模板名称"
            ></el-input>
          </el-form-item>
        </div> -->
        <!-- <div class="form-row">
          <el-form-item label="模板编码" prop="templateCode">
            <el-input 
              v-model="formData.templateCode"
              :disabled="dialogType === 'view'"
              placeholder="请输入模板编码"
            ></el-input>
          </el-form-item>
        </div> -->
        <div class="form-row">
          <el-form-item label="模板类型" prop="templateType" style="width: 80%;">
            <el-select 
              v-model="formData.templateType"
              :disabled="dialogType === 'view'"
              placeholder="请选择模板类型"
              style="width: 100%"
            >
              <el-option label="商品条码模板" value="product"></el-option>
              <el-option label="货位条码模板" value="location"></el-option>
              <el-option label="入库单模板" value="inbound"></el-option>
              <el-option label="拣选单模板" value="picking"></el-option>
              <el-option label="盘点单模板" value="inventory"></el-option>
			  <!-- <el-option label="基础模板" value="common"></el-option> -->
            </el-select>
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <dialog-footer 
          :cancel-text="dialogType === 'view' ? '关闭' : '取消'"
          confirm-text="确定"
          @cancel="dialogVisible = false" 
          @confirm="handleSubmit" 
          :show-confirm="dialogType !== 'view'"
        />
      </template>
    </el-dialog>
    
    <!-- 日志对话框 -->
    <log-dialog
      v-model:visible="logDialogVisible"
      :log-data="logData"
      :total="logPagination.total"
      :current-page="logPagination.currentPage"
      :page-size="logPagination.pageSize"
      @size-change="handleLogSizeChange"
      @current-change="handleLogCurrentChange"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

// 路由实例
const router = useRouter()

// 表格数据
const tableData = ref([])
const tableLoading = ref(false)
const selectedRows = ref([])

// 表格列配置
const tableColumns = [
  { type: 'selection', width: 50 },
  { prop: 'templateCode', label: '模板编码', minWidth: 120 },
  { prop: 'templateName', label: '模板名称', minWidth: 150 },
  { prop: 'templateType', label: '模板类型', minWidth: 100, formatter: (row) => {
    const typeMap = {
      'SF': '顺丰',
      'YTO': '圆通',
      'ZTO': '中通',
      'STO': '申通',
      'YD': '韵达',
      'JD': '京东',
      'CUSTOM': '自定义'
    }
    return typeMap[row.templateType] || row.templateType
  }},
  { prop: 'isDefault', label: '是否默认', minWidth: 80, formatter: (row) => row.isDefault ? '是' : '否' },
  { prop: 'createTime', label: '创建时间', minWidth: 180 },
  { prop: 'updateTime', label: '更新时间', minWidth: 180 },
  { prop: 'operation', label: '操作', fixed: 'right', width: 240, slotName: 'operation' }
]

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 搜索表单
const searchForm = reactive({
  templateCode: '',
  templateName: '',
  templateType: '',
})

// 搜索项配置
const searchItemsConfig = [
  {
    label: '模板编码',
    prop: 'templateCode',
    type: 'el-input',
    placeholder: '请输入模板编码',
    defaultVisible: true
  },
  {
    label: '模板名称',
    prop: 'templateName',
    type: 'el-input',
    placeholder: '请输入模板名称',
    defaultVisible: true
  },
  {
    label: '模板类型',
    prop: 'templateType',
    type: 'el-select',
    placeholder: '请选择模板类型',
    defaultVisible: true,
    options: [
      { label: '全部', value: '' },
      { label: '顺丰', value: 'SF' },
      { label: '圆通', value: 'YTO' },
      { label: '中通', value: 'ZTO' },
      { label: '申通', value: 'STO' },
      { label: '韵达', value: 'YD' },
      { label: '京东', value: 'JD' },
      { label: '自定义', value: 'CUSTOM' }
    ]
  }
]

// 操作按钮权限
const actionPermissions = reactive({
  add: true,
  delete: true,
  enable: true,
  disable: true
})

// 操作按钮配置
const buttonsConfig = reactive({
  add: { label: '新增', icon: 'Plus', show: true },
  delete: { label: '删除', icon: 'Delete', show: true, disabled: (selectedData) => selectedData.length === 0 },
  enable: { label: '启用', icon: 'Check', show: true, disabled: (selectedData) => selectedData.length === 0 },
  disable: { label: '停用', icon: 'Close', show: true, disabled: (selectedData) => selectedData.length === 0 }
})

// 表单对话框
const dialogVisible = ref(false)
const dialogType = ref('add') // add, edit, view
const dialogTitleMap = {
  add: '新增面单模板',
  edit: '编辑面单模板',
  view: '查看面单模板'
}

// 表单引用
const formRef = ref(null)

// 表单数据
const formData = reactive({
  id: '',
  templateCode: '',
  templateName: '',
  templateType: '',
  isDefault: false,
  remark: ''
})

// 表单验证规则
const formRules = {
  templateName: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
    { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
  ],
  templateCode: [
    { required: true, message: '请输入模板编码', trigger: 'blur' },
    { max: 30, message: '长度不能超过30个字符', trigger: 'blur' }
  ],
  templateType: [
    { required: true, message: '请选择模板类型', trigger: 'change' }
  ],
}

// 日志对话框
const logDialogVisible = ref(false)
const logData = ref([])
const logPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 初始化
onMounted(() => {
  fetchTableData()
})

// 获取表格数据
const fetchTableData = () => {
  // tableLoading.value = true
  
  // 模拟API请求
  // setTimeout(() => {
  //   const mockData = []
  //   for (let i = 1; i <= 20; i++) {
  //     mockData.push({
  //       id: `${i}`,
  //       templateCode: `TPL${String(i).padStart(3, '0')}`,
  //       templateName: `${['顺丰', '圆通', '中通', '申通', '韵达', '京东', '自定义'][i % 7]}快递面单模板${i}`,
  //       templateType: ['SF', 'YTO', 'ZTO', 'STO', 'YD', 'JD', 'CUSTOM'][i % 7],
  //       isDefault: i === 1,
  //       createTime: '2023-01-01 12:00:00',
  //       updateTime: '2023-01-02 15:30:00',
  //       remark: `模板描述信息${i}`
  //     })
  //   }
    
  //   // 过滤搜索条件
  //   const filteredData = mockData.filter(item => {
  //     if (searchForm.templateCode && !item.templateCode.includes(searchForm.templateCode)) return false
  //     if (searchForm.templateName && !item.templateName.includes(searchForm.templateName)) return false
  //     if (searchForm.templateType && item.templateType !== searchForm.templateType) return false
  //     return true
  //   })
    
  //   // 分页
  //   const startIndex = (pagination.currentPage - 1) * pagination.pageSize
  //   const endIndex = startIndex + pagination.pageSize
  //   tableData.value = filteredData.slice(startIndex, endIndex)
  //   pagination.total = filteredData.length
    
  //   tableLoading.value = false
  // }, 500)
}

// 表格选择改变
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchTableData()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchTableData()
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchTableData()
}

// 重置搜索
const handleReset = () => {
  pagination.currentPage = 1
  fetchTableData()
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 设计
const handleDesign = (row) => {
  router.push({
    path: '/configuration/print-management/designer',
    query: { id: row.id, name: row.templateName }
  })
}

// 预览
const handlePreview = (row) => {
  // 跳转到预览页面
  router.push({
    path: '/configuration/print-management/preview',
    query: { 
      id: row.id,
      name: row.templateName,
      type: row.templateType
    }
  });
}

// 设置默认模板
const handleSetDefault = (row) => {
  if (row.isDefault) {
    ElMessage.info('该模板已经是默认模板')
    return
  }
  
  ElMessageBox.confirm(
    `确定将"${row.templateName}"设置为默认模板吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟API请求
    setTimeout(() => {
      // 清除其他默认标记
      tableData.value.forEach(item => {
        item.isDefault = item.id === row.id
      })
      ElMessage.success('设置成功')
    }, 300)
  }).catch(() => {})
}

// 启用
const handleEnable = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择需要启用的记录')
    return
  }
  
  const ids = selectedRows.value.map(row => row.id)
  
  ElMessageBox.confirm(
    `确定启用选中的${ids.length}条记录吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟API请求
    setTimeout(() => {
      // 更新本地数据
      tableData.value.forEach(item => {
        if (ids.includes(item.id)) {
        }
      })
      ElMessage.success('启用成功')
    }, 300)
  }).catch(() => {})
}

// 停用
const handleDisable = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择需要停用的记录')
    return
  }
  
  const ids = selectedRows.value.map(row => row.id)
  
  ElMessageBox.confirm(
    `确定停用选中的${ids.length}条记录吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟API请求
    setTimeout(() => {
      // 更新本地数据
      tableData.value.forEach(item => {
        if (ids.includes(item.id)) {
        }
      })
      ElMessage.success('停用成功')
    }, 300)
  }).catch(() => {})
}

// 删除
const handleDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择需要删除的记录')
    return
  }
  
  const ids = selectedRows.value.map(row => row.id)
  
  ElMessageBox.confirm(
    `确定删除选中的${ids.length}条记录吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟API请求
    setTimeout(() => {
      // 更新本地数据
      tableData.value = tableData.value.filter(item => !ids.includes(item.id))
      pagination.total -= ids.length
      ElMessage.success('删除成功')
    }, 300)
  }).catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  dialogVisible.value = false
  await formRef.value.validate(async (valid) => {
    if (valid) {
      
	  router.push({
	    path: '/configuration/print-management/designer',
	    query: { type: formData.templateType }
	  })
    }
  })
}

// 日志相关操作 (模拟)
const handleLogSizeChange = (val) => {
  logPagination.pageSize = val
  // 获取日志数据
}

const handleLogCurrentChange = (val) => {
  logPagination.currentPage = val
  // 获取日志数据
}
</script>

<style lang="scss" scoped>
.express-template-container {
  height: 100%;
  padding: 10px 0;
  
  .dialog-form {
    max-height: 500px;
    overflow-y: auto;
    padding: 0 20px;
    
    .form-row {
      display: flex;
      margin-bottom: 10px;
      
      &.full-width {
        display: block;
      }
      
      .full-width-item {
        width: 100%;
      }
    }
  }
}
</style> 